#include "Skygen/DynamicCloudSkyboxGenerator.h"

#include "Core/Kernel.h"

namespace Orca {

	//--------------------------------------------------------------------------
	TDynamicCloudSkyboxGenerator::TDynamicCloudSkyboxGenerator() {

	}

	//--------------------------------------------------------------------------
	TDynamicCloudSkyboxGenerator::~TDynamicCloudSkyboxGenerator() {

	}

	//--------------------------------------------------------------------------
	Str TDynamicCloudSkyboxGenerator::getVertexProgramFilename() {

		return "Skygen/shader/Skybox_DynCloud_vp.glsl";
	}

	//--------------------------------------------------------------------------
	Str TDynamicCloudSkyboxGenerator::getFragmentProgramFilename() {

		return "Skygen/shader/Skybox_DynCloud_fp.glsl";
	}

	//--------------------------------------------------------------------------
	vec4 TDynamicCloudSkyboxGenerator::computeSkyboxColor(const vec3 &dir, int size) {

		vec3 result;

		float noise = 0.0f;
		
		float scale[] = {1.0f, 2.0f, 4.0f, 8.0f, 16.0f, 32.0f, 64.0f, 128.0f, 256.0f};

		for(int i=0; i<8; ++i) {

			vec3 pos = dir * scale[i] * 3.0f;
			float n = mIPN.pnoise( pos[0], pos[1], pos[2] );

			noise += n * (1.0f / scale[i]);
		}

		float noise2 = Math::clamp(1.0f * noise, 0.0f, 1.0f);

		// cloud rim light
		float shading = 1 - (noise2 * 1.0f);
		shading = Math::pow(shading, 8.0f);
		shading = Math::clamp(shading, 0.0f, 1.0f);

		float masking = noise * 2.0f + 0.2f;
		masking = Math::clamp(masking, 0.0f, 1.0f);
		
		result[0] = noise2;
		result[1] = masking * shading;
		result[2] = 0.0f;
		
		return toVec4(result, 1.0f);
	}

	//--------------------------------------------------------------------------
	void TDynamicCloudSkyboxGenerator::updateShaderConstants(Shader *shader) {

		float angle = (float)Kernel::inst()->getCurrentTime() * 0.0025f;
		mtx44 cloudMtx = rotateY(Math::deg2Rad(angle));

		shader->beginBinding();

		shader->bindMtx4("g_CloudMtx", cloudMtx);

		shader->endBinding();
	}

	//--------------------------------------------------------------------------
	void TDynamicCloudSkyboxGenerator::step(float dt) {

	}

	//--------------------------------------------------------------------------

}